#include <string.h>
#include <stdlib.h>
#include "plantillasLoad.h"

int plantillacount;

int loadPlantillas(char const *filename,struct PlantillaVars **data_ptr){
	FILE *ptr_file;///create FILE pointer
	ptr_file=fopen(filename,"r");///open file specified in *filename
	if(!ptr_file){
		return 1;
	}
	int maxlinelen;///used to allocate buffer length
	int numlines=getFileInfo(ptr_file,&maxlinelen);///used to allocate plantillas array size
	plantillacount=numlines;
	struct PlantillaVars *data;
	data=(struct PlantillaVars*) calloc(numlines,sizeof(struct PlantillaVars));///allocate plantilla array
	char *buf=(char*) malloc(maxlinelen*sizeof(char));///allocate buffer size
	char *tmp=(char*) malloc(20*sizeof(char));

	for(int i=0;i<numlines;i++){
		fgets(buf,maxlinelen,ptr_file);///load a line to buffer
		sscanf(strtok(buf,"-"), "%d", &data[i].userID);
		sscanf(strtok(NULL,"-"), "%d", &data[i].plantillaID);
		strcpy(data[i].name,strtok(NULL,"-"));
		sscanf(strtok(NULL,"-"), "%d", &data[i].budget);
		sscanf(strtok(NULL,"\n"), "%d", &data[i].points);
	}
	free(buf);
	fclose(ptr_file);
	*data_ptr=data;
	return 0;
}

int writePlantillas(char const *filename,struct PlantillaVars *data){
	FILE *ptr_file;
	ptr_file=fopen(filename,"w");
	if(!ptr_file){
		return 1;
	}
	///loop through plantillas
	for(int i=0;i<plantillacount;i++){
		///print a line
		fprintf(ptr_file,"%02d-%03d-%s-%d-%d\n",data[i].userID,data[i].plantillaID,data[i].name,data[i].budget,data[i].points);
	}
	fclose(ptr_file);
	//free(data);
	return 0;
}


void addPlantilla(struct PlantillaVars n,struct PlantillaVars **data_ptr){
	///reallocate plantilla array size and increment plantillacount
	struct PlantillaVars *data;
	data=(struct PlantillaVars*) realloc(*data_ptr,++plantillacount*sizeof(struct PlantillaVars));


	data[plantillacount-1]=n;
	*data_ptr=data;
}

void rmPlantilla(int index,struct PlantillaVars **data_ptr){
	struct PlantillaVars *data=(struct PlantillaVars*) calloc(plantillacount-1,sizeof(struct PlantillaVars));///allocate new array with one less element
	if(index!=0){
		memcpy(data,*data_ptr,index*sizeof(struct PlantillaVars));
	}
	//copy everything after index
	if(index < plantillacount){
		memcpy(data + index,*data_ptr + index + 1,(plantillacount - index - 1)*sizeof(struct PlantillaVars));
	}
	plantillacount--;
	free(*data_ptr);
	*data_ptr=data;
}
